package commons

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

/**
md5加密
*/
func EncodeMd5(value string) string {

	m := md5.New()
	m.Write([]byte(value))

	return hex.EncodeToString(m.Sum(nil))
}

/**
字符串转数字
*/

func StrToInt(s string) (int, bool) {
	i, err := strconv.Atoi(s)
	if CheckErr(err) {
		return i, true
	}
	return 0, false

}

/**
字符串拼接
*/
func StringJoin(a []string) string {
	var buf bytes.Buffer
	for _, k := range a {
		buf.WriteString(k)
	}
	fmt.Println(buf.String())
	return buf.String()
}

/**
简单的waf
*/
func StringFilter(s string, length int) bool {
	v := strings.TrimSpace(s)
	match, _ := regexp.MatchString(".*?<\\?|\\?>|>|\\(", v)

	if match {
		return false
	}
	if v != "" && len(v) >= length {
		return true
	}
	return false
}

/**
判断字符串是否为空
*/
func StringIsEmpty(s string, length int) bool {
	if strings.TrimSpace(s) != "" {
		if StringFilter(s, length) {
			return true
		}
	}
	return false
}

func BinarySearch(s []string, m string) int {
	//fmt.Printf("%v , %v", s, m)
	//针对对字符串
	if !StringFilter(m, 1) {
		return -1
	}

	for k, v := range s {
		if strings.EqualFold(v, m) {
			return k
		}
	}

	////_k := m[1 : len(m)-1]
	////k, _ := strconv.Atoi(m)
	//ints := sort.SearchStrings(s, m)
	//if ints == len(s) {
	//	return -1
	//} else {
	//	return ints
	//}
	////lo, hi := 0, len(s)-1
	////for lo <= hi {
	////	m := (lo + hi) >> 1
	////	if s[m] < k {
	////		lo = m + 1
	////	} else if s[m] > k {
	////		hi = m - 1
	////	} else {
	////		return m
	////	}
	////}
	return -1
}

func Abs(n int64) int64 {
	y := n >> 63
	return (n ^ y) - y
}
